package copm.atguigu.gulimall.cart.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import copm.atguigu.gulimall.cart.feign.ProductFeignservice;
import copm.atguigu.gulimall.cart.interceptor.CartInterceptor;
import copm.atguigu.gulimall.cart.service.CartService;
import copm.atguigu.gulimall.cart.vo.Cart;
import copm.atguigu.gulimall.cart.vo.CartItem;
import copm.atguigu.gulimall.cart.vo.SkuInfoDto;
import copm.atguigu.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {

    private final String CART_PREFIX = "gulimall:cart:";
    private static UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignservice productFeignservice;

    @Autowired
    private ThreadPoolExecutor executor;

    /**
     * 添加购物车
     **/
    @Transactional
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {

        BoundHashOperations<String, Object, Object> operations = getCartOps();
        /**
         * 先查询Redis中该上面是否存在,如果存在,就修改商品数量,如果不存在,才添加新商品
         **/
        String o = (String) operations.get(skuId.toString());

        if (StringUtils.isEmpty(o)) {
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> skuInfoTask = CompletableFuture.runAsync(() -> {
                //1: 远程查询sku的信息
                R r = productFeignservice.info(skuId);
                if (r.getCode() == 0) {
                    SkuInfoDto skuInfo = r.getDate("skuInfo", new TypeReference<SkuInfoDto>() {
                    });
                    //2: 商品添加到购物车
                    cartItem.setCheck(true);
                    cartItem.setCount(num);
                    cartItem.setImage(skuInfo.getSkuDefaultImg());
                    cartItem.setTitle(skuInfo.getSkuTitle());
                    cartItem.setSkuId(skuId);
                    cartItem.setPrice(skuInfo.getPreice());
                }
            }, executor);

            CompletableFuture<Void> skuSaleAttrValue = CompletableFuture.runAsync(() -> {
                //3: 远程查询商品的组合信息
                List<String> attrValue = productFeignservice.getSkusaleAttrValue(skuId);
                cartItem.setSkuAttr(attrValue);
            }, executor);

            CompletableFuture.allOf(skuInfoTask, skuSaleAttrValue).get();

            //将购物车信息存入Redis中
            String s = JSON.toJSONString(cartItem);
            operations.put(skuId.toString(), s);
            return cartItem;
        } else {
            CartItem cartItem = JSON.parseObject(o, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            String s = JSON.toJSONString(cartItem);
            operations.put(skuId.toString(), s);
            return cartItem;
        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> operations = getCartOps();
        String o = (String) operations.get(skuId.toString());
        if (o != null) {
            return JSON.parseObject(o, CartItem.class);
        }
        return null;
    }

    /**
     * 勾选购物车状态
     **/
    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1 ? true : false);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId, s);
    }

    /**
     * 获取购物车列表
     **/
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        if (userInfoTo.getUserId() != null) {
            //登录了
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //先获取临时购物车的数据
            List<CartItem> collect = getCartItem(CART_PREFIX + userInfoTo.getUserKey());
            if (!CollectionUtils.isEmpty(collect)) {
                //合并购物车
                for (CartItem cartItem : collect) {
                    addToCart(cartItem.getSkuId(), cartItem.getCount());
                }
                //合并后应该清楚临时购物车数据
                clearCart(CART_PREFIX + userInfoTo.getUserKey());
            }
            //获取合并后登录的购物车数据
            List<CartItem> cartItem = getCartItem(cartKey);
            cart.setItems(cartItem);
        } else {
            //没登录状态
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> collect = getCartItem(cartKey);
            cart.setItems(collect);
        }

        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    /**
     * 改变购物车商品的数量
     **/
    @Override
    public void changItemCount(Long skuId, Integer num) {

        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId, s);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId);
    }

    @Override
    public List<CartItem> getCurrentUserCartItems() {

        if (userInfoTo.getUserId() != null) {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItem = getCartItem(cartKey);
            List<CartItem> collect = cartItem.stream().filter(item -> item.getCheck()).map(item -> {

                //更新商品价格为当前最新价格
                R price = productFeignservice.getPrice(item.getSkuId());
                if (price.getCode() == 0) {
                    String data = (String) price.get("data");
                    item.setPrice(new BigDecimal(data));
                }
                return item;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 获取购物车详情
     **/
    private List<CartItem> getCartItem(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (!CollectionUtils.isEmpty(values)) {
            List<CartItem> collect = values.stream().map(obj -> {
                String s = obj.toString();
                CartItem cartItem = JSON.parseObject(s, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }

        return null;
    }

    /**
     * 获取到我们要操作的购物车
     **/
    private BoundHashOperations<String, Object, Object> getCartOps() {
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            //表示用户已经登录了
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }
}
